(async ()=>{
    // "use strict"; // 全局严格模式
    document.documentElement.style.fontSize = (window.innerWidth / 750) + 'px'


    let bannerBox = document.querySelector('#bannerBox')
    let banner = bannerBox.querySelector('.banner')
    banner.innerHTML = ''//清空之前图片
    let instructs = bannerBox.querySelector('.instructs')
    instructs.innerHTML = ''

    let bannerData = await (await fetch('http://localhost:3001/index/banners')).json()

    let bannerImgs = [],instructDivs = []

    
    for(let i = 0; i < bannerData.length; i ++){
        ((i)=>{
                  let data = bannerData[i]
            //插入图片
            let _banner = document.createElement('img')
            _banner.src = 'http://localhost:3001' + data.img
            _banner.onclick = ()=>{
                window.open(data.url)
            }
            banner.appendChild(_banner)
            bannerImgs.push(_banner)

            //插入指示器
            let instruct = document.createElement('div')
            instruct.className = 'instruct'
            instruct.onclick = () => {
                bannerPlay(i)
            }
            instructs.appendChild(instruct)
            instructDivs.push(instruct)
        })(i)
    }
    let cloneFirst = bannerImgs[0].cloneNode()
    banner.appendChild(cloneFirst)

    //设置banner长度
    banner.style.width = 676 * (bannerData.length + 1) + 'rem'

    let bannerIndex = 0
    let bannerTimer = 0
    function bannerPlay(i){
        instructDivs[bannerIndex].style.background = '#fff'
        bannerIndex = i
        //修改新的焦点状态
        banner.style.marginLeft = '-' + i * 676 + 'rem'
        instructDivs[bannerIndex == bannerImgs.length ? 0 : bannerIndex].style.background = '#ff0000'
        if(bannerTimer){
            clearTimeout(bannerTimer)
            bannerTimer = 0
        }
        if(bannerIndex == bannerImgs.length){
            setTimeout(()=>{
                bannerIndex = 0
                i = 0
                banner.className = 'banner'
                banner.style.marginLeft = '0rem'
                setTimeout(() => {
                    banner.className = 'banner bannerAnmate'
                },100)
            },1000)
        }
        //开始计时轮播
        
        bannerTimer = setTimeout(()=>{
            bannerPlay(i + 1)
        },5000)
    }
    bannerPlay(0)



    // 获取数据
    let response = await fetch('http://localhost:3001/index/categorys');
    let data = await response.json();
    
    // 获取元素
    let imagesDiv = document.querySelector('.fenlei');
    let titlesDiv = document.querySelector('.zizi');
    
    // 清空原有内容
    imagesDiv.innerHTML = '';
    titlesDiv.innerHTML = '';
    
    // 遍历数据，创建元素并添加到页面
    for (let i = 0; i < data.length; i++) {
        let img = document.createElement('img');
        img.src = 'http://localhost:3001' + data[i].img;
        img.className = 'new-img tall-img can-img all-img';
        imagesDiv.appendChild(img);
    
        let title = document.createElement('div');
        title.className = 'zizi1 zizi2 zizi2 zizi2';
        title.textContent = data[i].title;
        title.addEventListener('click', function() {
            window.location.href = 'http://127.0.0.1:5500/2024/shangpinliebiao.html';
        });
        titlesDiv.appendChild(title);
    }
    
    //首页新闻轮播
    const titleElement = document.getElementById('title');
    const url1 = 'http://localhost:3001/index/news';
    
    function fetchNews() {
        fetch(url1)
            .then(response => response.json())
            .then(data => {
                let titles = data.map(item => item.title);
                let currentIndex = 0;
                function changeTitle() {
                    titleElement.innerText = titles[currentIndex];
                    currentIndex = (currentIndex + 1) % titles.length;
                }
                setInterval(changeTitle, 3000);
            })
            .catch(error => console.error('Error fetching news:', error));
    }
    
    fetchNews();
    
    // fetch('http://localhost:3001/index/recommends')
    //   .then(response => response.json())
    //   .then(data => {
    //     const adverElements = document.querySelectorAll('.zhekou');
    //     const titleElements = document.querySelectorAll('.xinping');
    
    //     data.rows.forEach((recommend, index) => {
    //       adverElements[index].innerHTML = `<img src="http://localhost:3001${recommend.img}" alt="${recommend.title}">`;
    //       titleElements[index].textContent = recommend.title;
    //     });
    //   })
    //   .catch(error => console.error('Error fetching data:', error));
    
    
        // // 获取数据
        // let responsed = await fetch('http://localhost:3001/index/recommends');
        // let datas = await response.json();
        
        // // 获取元素
        // let imagesDiv1 = document.querySelector('.zekou');
        // let titlesDiv1 = document.querySelector('.xinping');
        
        // // 清空原有内容
        // imagesDiv1.innerHTML = '';
        // titlesDiv1.innerHTML = '';
        
        // // 遍历数据，创建元素并添加到页面
        // for (let i = 0; i < data.length; i++) {
        //     let img = document.createElement('img');
        //     img.src = 'http://localhost:3001' + data[i].img;
        //     img.className = 'zhekou';
        //     imagesDiv.appendChild(img);
        
        //     let title = document.createElement('div');
        //     title.className = 'xinping';
        //     title.textContent = data[i].title;
        //     titlesDiv.appendChild(title);
        // }








    //放内容元素
    let recommends = document.querySelector('#recommends')
    //提示信息元素
    let recommendMsg = document.querySelector('#recommendMsg')
    //  当前页        总数      已加载缓存
    let pageNum = 1, total = 0, recommendDatas = []
    //加载下一页
    recommendMsg.addEventListener('click', () => {
        //已全部加载就什么都不做了
        if (total <= recommendDatas.length) return
        //获取下一页数据
        pageNum++
        loadRecommends()
    })
    //获取数据
    async function loadRecommends() {
        recommendMsg.innerHTML = '加载中...'
        //获取数据
        let res = await (await fetch(`http://localhost:3001/index/recommends?pageNum=${pageNum}`)).json()
        total = res.total
        //插入获取的数据
        for (let i = 0; i < res.rows.length; i++) {
            let recommend = document.createElement('div')
            let recommendData = res.rows[i]
            let img = document.createElement('img')
            img.src = 'http://localhost:3001' + res.rows[i].img

            //已获取数据加入缓存
            recommendDatas.push(recommendData)
            //构建内容
            recommend.className = 'recommend'
            recommend.innerHTML = `
            <img src="${img.src}" />
            <a href="${recommendData.url}" style="display:block;">
                <div class="recommend_text">
                    <div class="title">${recommendData.title}</div>
                    <div class="detail">
                        <div class="detail_text">查看详情</div>
                        <div style="width: 12rem;height: 12rem;margin-top: -30rem;margin-left: 150rem;">></div>
                    </div>
                </div>

            </a>
            `
            //为“查看详情”的链接添加点击事件监听器
            recommend.querySelector('.detail_text').addEventListener('click', function(event) {
                event.preventDefault() // 阻止默认行为
                window.location.href = 'http://127.0.0.1:5500/2024/HomeBrand.html' // 设置要跳转的页面地址
            })
            //展示新增数据
            recommends.appendChild(recommend)
        }
        //判断提示信息内容
        recommendMsg.innerHTML = total > recommendDatas.length ? '点击加载更多' : '已经到底了哦~'
    }

    loadRecommends()


})()